package com.chipcoo.web.servlet;

import com.chipcoo.ResponseResult;
import com.chipcoo.captcha.geetest.GeetestLib;
import com.chipcoo.utils.StringUtils;
import com.chipcoo.utils.ValidateUtils;
import com.chipcoo.web.servlet.view.FastJsonJsonView;
import com.chipcoo.web.utils.MediaTypeUtils;
import com.chipcoo.web.utils.ViewUtils;
import com.chipcoo.web.utils.WebUtils;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Map;

public class DispatcherServlet extends org.springframework.web.servlet.DispatcherServlet {

    @Override
    protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale, HttpServletRequest request) throws Exception {
        View view =  super.resolveViewName(viewName, model, locale, request);
        if(null!=view){
            if(view instanceof FastJsonJsonView) {
                if (model.containsKey("responseResult")) {
                    ResponseResult responseResult = null;
                    Object objectResponseResult = model.get("responseResult");

                    if (null == objectResponseResult) {
                        responseResult = new ResponseResult();
                    } else {
                        responseResult = (ResponseResult) objectResponseResult;
                    }

                    Object captchaChallenge = ValidateUtils.getCaptchaChallenge();
                    if (null != captchaChallenge) {
                        if (null == responseResult.getData() || responseResult.getData() instanceof Map) {
                            responseResult.put("gt", GeetestLib.CAPTCHA_ID)
                                    .put("challenge", captchaChallenge);
                        }
                    }
                    if (!MediaTypeUtils.isAjax(request) && null != responseResult.get(ResponseResult.KEY_REDIRECT)) {
                        view = ViewUtils.redirectView(WebUtils.getURL(responseResult, request));
                    }
                }
            }
        }
        return view;
    }
}
